class Student < ActiveRecord::Base
  require 'fixnum_overrides'
  belongs_to :major
  has_many :semester_registrations
  has_many :semesters, :through => 'semester_registration'
  has_and_belongs_to_many :sections
  
  has_many  :futures
  has_many  :pasts
  
  has_many :courses_taken, :through => :pasts, :source => 'course'
  has_many :courses_to_take, :through => :futures, :source => 'course'
  
  has_many :semesters_taken, :through => :pasts, :source => 'semester'
  has_many :semesters_to_take, :through => :futures, :source => 'semester'
  
  
  def has_taken?(course)
    return false if self.courses_taken.nil?
    return self.courses_taken.include?(course)
  end
  
  def courses_for_future_semester(semester)
    self.futures.select { |e| e.semester == semester }.collect { |e| e.course }.sort
  end
  
  def hours_in_future_semester(semester)
    hours = 0
    self.courses_for_future_semester(semester).each { |e| hours = hours + e.hours }
    return hours
  end
  
  def future_with_course(course)
    self.futures.select { |e| e.course == course }[0]
  end
  
  def future_semesters_except(semester)
    self.futures.collect { |e| e.semester }.uniq.reject { |e| e == semester }
  end
  
  def current_open_registration
    today = Time.now
    self.semester_registrations.select { |e| (e.open_datetime <=  today) and (e.close_datetime >= today)}.first
  end
  
  def technical_electives_taken
    self.major.technical_electives.intersection self.courses_taken
  end
  
  def technical_electives_taking
    self.courses_to_take.intersection self.major.technical_electives
  end
  
  def technical_elective_hours_left
    total_to_take = self.major.technical_elective_hours
    total_taken = 0
    electives_taking_and_taken = (self.technical_electives_taken + self.technical_electives_taking)
    return total_to_take if electives_taking_and_taken.empty?
    self.technical_electives_taking.each { |e| total_taken = total_taken + e.hours }
    return (total_to_take - total_taken).closest_nonnegative
  end
end
